package thread;

/**
 * 异步线程回调任务
 * @author jinmiao
 * 2014-9-12 上午10:58:57
 */
public abstract class DisruptorAsyncBackTask extends DisruptorAsyncTask
{
	
	public DisruptorAsyncBackTask(String callExecuteName) {
		super(callExecuteName);
	}
	
	/**
	 * 执行的线程池
	 */
	protected BaseDisruptorExecutor executor;
	
	/**回调回来的线程名字**/
	private String backThreadName = Thread.currentThread().getThreadGroup().getName();
	
	private volatile boolean isAsyncOver;
	
	@Override
	public void execute() throws Throwable {
		long start = System.currentTimeMillis();
		//执行异步
		if(!isAsyncOver)
		{
			this.threadName = backThreadName;
			super.execute();
			isAsyncOver = true;
			executor.publishTask(this);
		}
		else
		{
			//执行回调
			try {
				if(e ==null)
					doCallBack();
				else
					onFail(e);
			} catch (Exception e) {
				if (logger.isErrorEnabled()) {
					logger.error("Error", "#.DisruptorAsyncBackTask.execute", "param", e);
				}	
			}
		}
		long useTime = System.currentTimeMillis()-start;
		if(useTime>1)
		{
			logger.error("异步回调耗时"+getClass().getName()+" "+ useTime);
		}	
	}
	
	protected abstract void onFail(Throwable e);

	/**
	 * 异步处理完后回原线程做处理
	 */
	protected abstract void doCallBack();

}
